package com.namuan.jp_stock.activity;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.namuan.jp_stock.object.ActivityComment;
import com.namuan.jp_stock.object.FullActivity;
import com.namuan.jp_stock.object.Timestamp;
import com.namuan.jp_stock.util.AsyncJustplaceRunner;
import com.namuan.jp_stock.util.BaseRequestListener;
import com.namuan.jp_stock.util.CustomImageManager;
import com.namuan.jp_stock.util.ImageManager;
import com.namuan.jp_stock.util.Justplace;
import com.namuan.jp_stock.util.JustplaceError;
import com.namuan.jp_stock.util.ObjUtils;
import com.namuan.jp_stock.util.PointImageView;
import com.namuan.jp_stock.util.ProfileImageView;
import com.namuan.jp_stock.util.SessionStore;
import com.namuan.jp_stock.util.Util;

import com.namuan.jp_stock.R;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class DetailActivity extends Activity  implements OnClickListener{
	private Activity activity;
	private Justplace mJustplace;
	
	private AsyncJustplaceRunner mAsyncRunner;
	
	
	private ProgressDialog progressdialog_;
	private ImageButton headerWriteBtn;
	private TextView userHeaderNickname;
	
	private LinearLayout lLayoutScrollView;
	
	EditText editComment;
	EditText editHidden;
	ImageButton imgBtnComment;
	

	
	private ProfileImageView activityUserImg;
	private PointImageView profileActivityUserImg;
	private TextView tvActivityUserNickname;
	private TextView tvActivityRecommendation; //
	private TextView tvActivityTimeStamp;
	private TextView tvActivityComment;
	private ImageView imgBtnRecommendation;
	
	private TextView tvActivitySummary;
	//private ImageView imgTwitter;
	//private ImageView imgFacebook;
	//private TextView tvTBcount;
	private TextView tvActivityCommentCount;
	
	private ImageView navBtn1;
	private ImageView navBtn2;
	private ImageView navBtn3;
	private ImageView navBtn4;
		
	//comment list 관련
	private View[] viewCommentList;
	private View footAddComment;
	
	private String loginNick = null;
	
	private String strActivityid;
	private String activityUserNickStr;
	
	private FullActivity fullactivity;
	
	private ArrayList<ActivityComment> commentItems = new ArrayList<ActivityComment>();
	private int activityCommentsCount;
	
	public CustomImageManager customImageManager;



		

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LoginActivity.activityList.add(this);
		setContentView(R.layout.detail_activity);
		this.activity = this;
		strActivityid = getIntent().getStringExtra("activityid");

		headerWriteBtn = (ImageButton) findViewById(R.id.headerWriteBtn);
		
		userHeaderNickname = (TextView) findViewById(R.id.userHeaderNickname);
		RelativeLayout activityUserRLayout = (RelativeLayout) findViewById(R.id.activityUserRLayout);
		
		lLayoutScrollView = (LinearLayout) findViewById(R.id.lLayoutScrollView);
		activityUserImg = (ProfileImageView) findViewById(R.id.activityUserImg);
		userHeaderNickname = (TextView) findViewById(R.id.userHeaderNickname);
		tvActivityComment = (TextView) findViewById(R.id.tvActivityComment);
		tvActivityTimeStamp = (TextView) findViewById(R.id.tvActivityTimeStamp);
		tvActivityUserNickname = (TextView) findViewById(R.id.tvActivityUserNickname);
		//tvTBcount = (TextView) findViewById(R.id.tvTBcount);
		tvActivityCommentCount = (TextView) findViewById(R.id.tvActivityCommentCount);
		tvActivityRecommendation = (TextView) findViewById(R.id.tvActivityRecommendation);
		tvActivitySummary =  (TextView) findViewById(R.id.tvActivitySummary);
		
		
		
		navBtn1 = (ImageView) findViewById(R.id.navBtn1);
		navBtn2 = (ImageView) findViewById(R.id.navBtn2);
		navBtn3 = (ImageView) findViewById(R.id.navBtn3);
		navBtn4 = (ImageView) findViewById(R.id.navBtn4);

		
		headerWriteBtn.setOnClickListener(this);
		userHeaderNickname.setOnClickListener(this);

		activityUserImg.setOnClickListener(this);
		activityUserRLayout.setOnClickListener(this);
		tvActivityUserNickname.setOnClickListener(this);
		
		navBtn1.setOnClickListener(this);
		navBtn2.setOnClickListener(this);
		navBtn3.setOnClickListener(this);
		navBtn4.setOnClickListener(this);
		

		mJustplace = new Justplace();
		SessionStore.restore(mJustplace, this);
		loginNick = mJustplace.getmUserNickname();
		mAsyncRunner = new AsyncJustplaceRunner(mJustplace);
		//showDialog(DIALOG_PROGRESS_ID);
		init();
		mJustplace.setHeader(userHeaderNickname);

	}
	
	private void init() {
		Bundle params = new Bundle();
		params.putString("activityid", strActivityid);
		/**/mAsyncRunner.request("loadfullactivity.do", params, "GET",
				new LoadFullActivityRequestListener(), null);
				/**/
		progressdialog_ = new ProgressDialog(this);
    	progressdialog_.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    	progressdialog_.setTitle("Loading");
    	progressdialog_.setMessage("잠시만 기다려주세요");
    	progressdialog_.show();
	}
	public class LoadFullActivityRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			try {

				Log.d("StockSns-FullMain", "Response: " + response.toString());
				JSONObject json = Util.parseJson(response);
				if (json.getBoolean("state")) {
					fullactivity = ObjUtils.jsonToFullActivity(json.getJSONObject("fullactivity"));
					if(json.has("activityCommentList")){
						ArrayList<ActivityComment> activityComments = ObjUtils.jsonToActivityComment(json
								.getJSONArray("activityCommentList"));
						activityCommentsCount = activityComments.size();
						for (ActivityComment activityComment : activityComments) {
							commentItems.add(activityComment);
						}
					}
				}
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						CustomImageManager cutomImageManager = new CustomImageManager(activity.getApplicationContext(), R.drawable.defaultuser);
						if (fullactivity.getProfilepic() != null
								&& !fullactivity.getProfilepic().equals("null")) {
							activityUserImg.setTag(Justplace.PROFILEIMG_URL + fullactivity.getProfilepic());
							cutomImageManager.displayImage(Justplace.PROFILEIMG_URL + fullactivity.getProfilepic(), activity, activityUserImg);

						} else {
							activityUserImg.setTag(null);
							cutomImageManager.displayImage(fullactivity.getProfilepic(), activity, activityUserImg);
						}						
						tvActivityComment.setText(fullactivity.getComment());
						//tvActivityTimeStamp.setText(new Timestamp().timestmsp(fullactivity.getTimestamp()));
						activityUserNickStr = fullactivity.getUsernickname();
						tvActivityUserNickname.setText(activityUserNickStr);
						tvActivitySummary.setText("("+fullactivity.getStockname() + " @ 주식SNS)" );
						//tvTBcount.setText(trackbackCount.toString());
						tvActivityCommentCount.setText(fullactivity.getTrackbackcount());
						tvActivityRecommendation.setText(fullactivity.getRecommendation());
						
						if(activityCommentsCount != 0) {
							DrawComment();
									//scrollView1.fullScroll(ScrollView.FOCUS_DOWN);
							/*  댓글이 없는 경우 - 따질 필요 없다 ( response가 널인지 확인 ) 
							if (commentItems.size() == 0) {
								// findViewById(R.id.tvNoJusting).setVisibility(View.VISIBLE);
							}
							else {
								
							}*/
						} else { //댓글이 없는경우
							LayoutInflater mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
							footAddComment = mInflater.inflate(R.layout.foot_addcomment, null);
							
							lLayoutScrollView.addView(footAddComment);
							editComment = (EditText) footAddComment.findViewById(R.id.editComment);
							imgBtnComment = (ImageButton) footAddComment.findViewById(R.id.imgBtnComment);
							imgBtnComment.setOnClickListener((OnClickListener) activity);
							
							//scrollView1.scrollTo(lLayoutScrollView.getWidth(), lLayoutScrollView.getHeight());
							// findViewById(R.id.lLayoutScrollView);
							if(progressdialog_.isShowing())
								progressdialog_.dismiss();
						}
					}
				});
				

			} catch (JSONException e) {
				Log.w("StockSns-FullMain", "JSON Error in response");
			} catch (JustplaceError e) {
				Log.w("StockSns-FullMain", "StockSns Error: " + e.getMessage());
			}
		}// onComplete out
	}// class out
		
	public class LoadActivityCommentRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			Log.d("StockSns-FullMain", "Response: " + response.toString());
			try {
				if (commentItems != null)
					commentItems.clear();
				else
					commentItems = new ArrayList<ActivityComment>();
				Log.d("StockSns-FullMain", "Response: " + response.toString());

				JSONObject json = Util.parseJson(response);
				if ( !json.getString("state").equals("false") ){
					ArrayList<ActivityComment> activityComments = ObjUtils
							.jsonToActivityComment(json
									.getJSONArray("activityCommentList"));
					activityCommentsCount = activityComments.size();
					for (ActivityComment activityComment : activityComments) {
						commentItems.add(activityComment);
					}
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							DrawComment();
							//scrollView1.fullScroll(ScrollView.FOCUS_DOWN);
						}

					});
					/*  댓글이 없는 경우 - 따질 필요 없다 ( response가 널인지 확인 ) 
					if (commentItems.size() == 0) {
						// findViewById(R.id.tvNoJusting).setVisibility(View.VISIBLE);
					}
					else {
						
					}*/
				} else { //댓글이 없는경우
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							
							LayoutInflater mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
							footAddComment = mInflater.inflate(R.layout.foot_addcomment, null);
							
							lLayoutScrollView.addView(footAddComment);
							editComment = (EditText) footAddComment.findViewById(R.id.editComment);
							/*
							editHidden = (EditText)  footAddComment.findViewById(R.id.editHidden);
							InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
							imm.hideSoftInputFromWindow(editHidden.getWindowToken(), 0);
							editHidden.requestFocus();
							*/
							imgBtnComment = (ImageButton) footAddComment.findViewById(R.id.imgBtnComment);
							imgBtnComment.setOnClickListener((OnClickListener) activity);
							
							//scrollView1.scrollTo(lLayoutScrollView.getWidth(), lLayoutScrollView.getHeight());
							// findViewById(R.id.lLayoutScrollView);
							if(progressdialog_.isShowing())
								progressdialog_.dismiss();
						}
					});
				}
			} catch (JSONException e) {
				Log.w("StockSns-FullMain", "JSON Error in response");
			} catch (JustplaceError e) {
				Log.w("StockSns-FullMain", "StockSns Error: " + e.getMessage());
			}
		}
		
		
	}
	public class InsertActivityCommentRequestListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
        	 Log.d("StockSNS-FullMain", "Response: " + response.toString());
        }
    }
	
	private void DrawComment() {
		if(footAddComment != null)
			lLayoutScrollView.removeView(footAddComment);
		if (viewCommentList != null) {
			int commentCount = viewCommentList.length;
			// LinearLayout lLayoutCommentList = (LinearLayout)
			// findViewById(R.id.lLayoutCommentList);
			for (int i = 0; i < commentCount; i++)
				lLayoutScrollView.removeView(viewCommentList[i]);
			viewCommentList = null;
			lLayoutScrollView.removeView(footAddComment);
		}
		viewCommentList = new View[commentItems.size()];

		LayoutInflater mInflater = (LayoutInflater) activity
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		// LinearLayout layout = new LinearLayout(activity);
		// layout.setVisibility(View.VISIBLE);
		
		footAddComment = mInflater.inflate(R.layout.foot_addcomment, null);
		editComment = (EditText) footAddComment.findViewById(R.id.editComment);
		imgBtnComment = (ImageButton) footAddComment.findViewById(R.id.imgBtnComment);
		imgBtnComment.setOnClickListener((OnClickListener) activity);
		editHidden = (EditText)  footAddComment.findViewById(R.id.editHidden);
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(editHidden.getWindowToken(), 0);

		for (int i = 0; i < commentItems.size(); i++) {
			viewCommentList[i] = new View(activity);
			viewCommentList[i] = mInflater.inflate(R.layout.comment_row, null);
			activityUserImg = (ProfileImageView) viewCommentList[i].findViewById(R.id.activityUserImg);
			TextView userProfileNickText = (TextView) viewCommentList[i]
					.findViewById(R.id.activityUserNick);

			tvActivityTimeStamp = (TextView) viewCommentList[i]
					.findViewById(R.id.activityTimeStamp);
			TextView activityCommentText = (TextView) viewCommentList[i]
					.findViewById(R.id.activityComment);
			final ActivityComment activityComment = commentItems.get(i);
			int length = activityComment.getProfilepic().length();
			String profilepic = activityComment.getProfilepic().substring(0, length);
			ImageManager imageManager = new ImageManager(activity.getApplicationContext(), R.drawable.defaultuser);
			if (profilepic != null && !profilepic.equals("null")) {
				 activityUserImg.setTag(Justplace.PROFILEIMG_URL  + profilepic);
				 Log.d("!!!!!!!!!!!!!!!!!!!!!!!!", Justplace.PROFILEIMG_URL + profilepic);
				 //customImageManager.displayImage(Justplace.TEST_URL + profilepic, activity, activityUserImg);
				 imageManager.displayImage(Justplace.PROFILEIMG_URL + profilepic, activity, activityUserImg);
			} else {
				activityUserImg.setTag(null);
				//customImageManager.displayImage(profilepic,
				//		activity, activityUserImg);
				imageManager.displayImage(profilepic, activity, activityUserImg);
			}
			
			activityUserImg.setOnClickListener(new OnClickListener() {
				@Override
				/* 보완 - myprofile or userprofile */
				public void onClick(View v) {
					if (activityUserNickStr.equals( userHeaderNickname.getText() )) {
						Intent activityUserIdintent = new Intent(activity, MyProfileActivity.class);
						activity.startActivity(activityUserIdintent);
						overridePendingTransition(R.anim.fade, R.anim.hold);
					} else {// 타유저의 activity의 id 클릭
						Intent activityUserIdintent = new Intent(activity, UserProfileActivity.class);
						activityUserIdintent.putExtra("usernick", activityUserNickStr);
						activity.startActivity(activityUserIdintent);
						overridePendingTransition(R.anim.fade, R.anim.hold);
					}
				}
			});
			// 2. 텍스트 : 유저id
			userProfileNickText.setText(activityComment.getUserid());

			userProfileNickText.setOnClickListener(new OnClickListener() {
				@Override
				/* 보완 - myprofile or userprofile */
				public void onClick(View v) {
					if (activityUserNickStr.equals( userHeaderNickname.getText() )) {
						Intent activityUserIdintent = new Intent(activity, MyProfileActivity.class);
						activity.startActivity(activityUserIdintent);
						overridePendingTransition(R.anim.fade, R.anim.hold);
					} else {// 타유저의 activity의 id 클릭
						Intent activityUserIdintent = new Intent(activity, UserProfileActivity.class);
						activityUserIdintent.putExtra("usernick", activityUserNickStr);
						activity.startActivity(activityUserIdintent);
						overridePendingTransition(R.anim.fade, R.anim.hold);
					}
				}
			});

			// 3. 텍스트 : 타임 스탬프
			tvActivityTimeStamp.setText(new Timestamp()
					.timestmsp(activityComment.getTimestamp()));
			// 4. 텍스트 : 코멘트
			activityCommentText.setText(activityComment.getComment());
			lLayoutScrollView.addView(viewCommentList[i]);
		}
		lLayoutScrollView.addView(footAddComment);
		//editHidden.requestFocus();
		if(progressdialog_.isShowing())
			progressdialog_.dismiss();
	}
	@Override
	public void onClick(final View v) {
		switch (v.getId()) {

		// get Tweets ��ư Ŭ��
		
		case R.id.headerWriteBtn:
			Intent Insert_intent = new Intent(this, AddActivity.class);
		      this.startActivity(Insert_intent);
		      overridePendingTransition(R.anim.fade, R.anim.hold);
			break;
		case R.id.userHeaderNickname:
			Intent userHeaderNicknameintent = new Intent(this, MyProfileActivity.class);
		      this.startActivity(userHeaderNicknameintent);
		      overridePendingTransition(R.anim.fade, R.anim.hold);
			break;
			
			
		case R.id.activityUserRLayout:
			if (tvActivityUserNickname.getText().equals( userHeaderNickname.getText() )) {
				Intent activityUserintent = new Intent(this, MyProfileActivity.class);		
				this.startActivity(activityUserintent);
				overridePendingTransition(R.anim.fade, R.anim.hold);
			} else {// 타유저의 activity의 id 클릭
				Intent activityUserintent = new Intent(this, UserProfileActivity.class);
				activityUserintent.putExtra("usernick", activityUserNickStr);
				this.startActivity(activityUserintent);
				overridePendingTransition(R.anim.fade, R.anim.hold);
			}
			break;
			// 아래꺼랑 동일
		case R.id.activityUserImg:
			if (tvActivityUserNickname.getText().equals( userHeaderNickname.getText() )) {
				Intent activityUserintent = new Intent(this, MyProfileActivity.class);		
				this.startActivity(activityUserintent);
				overridePendingTransition(R.anim.fade, R.anim.hold);
			} else {// 타유저의 activity의 id 클릭
				Intent activityUserintent = new Intent(this, UserProfileActivity.class);
				activityUserintent.putExtra("usernick", activityUserNickStr);
				this.startActivity(activityUserintent);
				overridePendingTransition(R.anim.fade, R.anim.hold);
			}
			break;
			// 자신의  activity인지 상대방의 activity인지 확인
		case R.id.activityUserNickname:
			// 내 activiy의 id 클릭
			if (tvActivityUserNickname.getText().equals( userHeaderNickname.getText() )) {
				Intent activityUserintent = new Intent(this, MyProfileActivity.class);		
				this.startActivity(activityUserintent);
				overridePendingTransition(R.anim.fade, R.anim.hold);
			} else {// 타유저의 activity의 id 클릭
				Intent activityUserintent = new Intent(this, UserProfileActivity.class);
				activityUserintent.putExtra("usernick", activityUserNickStr);
				this.startActivity(activityUserintent);
				overridePendingTransition(R.anim.fade, R.anim.hold);
			}
			break;
		case R.id.navBtn1:// home
			Intent navBtn1intent = new Intent(this, MainActivity.class);
			navBtn1intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
			this.startActivity(navBtn1intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
			finish();
			break;

		case R.id.navBtn2:// stock line
			/*
			Intent navBtn2intent = new Intent(this, StockActivity.class);
			this.startActivity(navBtn2intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);*/
			//finish();
			break;
			
		case R.id.navBtn3:// friends line
			/*
			Intent navBtn3intent = new Intent(this, FriendsActivity.class);
			this.startActivity(navBtn3intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);*/
			//finish();
			break;
			
		case R.id.navBtn4:// profile
			/*
			Intent navBtn4intent = new Intent(this, MyProfileActivity.class);
			this.startActivity(navBtn4intent);
			overridePendingTransition(R.anim.fade, R.anim.hold);
			*/
			//finish();
			break;
			
		case R.id.imgBtnComment:
			// 코멘트를 입력했는지
			String comment = editComment.getText().toString();
			if(editComment.getText() == null || editComment.length() < 1 ){
				AlertDialog.Builder alert = new AlertDialog.Builder(
						activity);
				alert.setPositiveButton("확인",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(
									DialogInterface dialog,
									int which) {
								dialog.dismiss(); // 닫기
							}
						});
				alert.setMessage("Comment를 5글자 이상 입력해주세요.");
				alert.show();
			} else {
				Bundle params = new Bundle();
				params.putString("activityid", strActivityid);
				params.putString("usernickname", loginNick);
				params.putString("comment", comment );
				//params.putString("timestamp", timestamp);
				progressdialog_ = new ProgressDialog(this);
		    	progressdialog_.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		    	progressdialog_.setTitle("Loading");
		    	progressdialog_.setMessage("잠시만 기다려주세요");
		    	progressdialog_.show();
				mAsyncRunner.request("insertractivitycomment.do", params, "POST",
								new InsertActivityCommentRequestListener(), null);
				
				//params.putString("activityid", activityid);
				mAsyncRunner.request("loadactivitycomment.do", params, "GET",
						new LoadActivityCommentRequestListener(), null);
			}		
			break;
		}
	}
}